package com.cbwl.eoas.common.util;

import org.apache.commons.codec.binary.Hex;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * author: Administrator
 * created on: 2017/11/2 8:51
 * description:
 */
public class DigestUtil {

    private static final String KEY = "Ukk5TKwCKvMPB75QDQM0Og==";

    @SuppressWarnings("unchecked")
    public static String digest(Map<String, ?> map) {
        StringBuilder s = new StringBuilder();
        List<String> list = new ArrayList<String>();
        for (Object values : map.values()) {
            if (values instanceof String[]) {
                for (String value : (String[]) values) {
                    if (value == null) {
                        value = "";
                    }
                    list.add(value);
                }
            } else if (values instanceof List) {
                for (String value : (List<String>) values) {
                    if (value == null) {
                        value = "";
                    }
                    list.add(value);
                }
            } else {
                if (values == null) {
                    values = "";
                }
                list.add((String) values);
            }
        }
        Collections.sort(list);
        for (String str : list) {
            s.append(str);
        }
        return digest(s.toString());
    }
    
    
    public static String digest(String content) {
        try {
            Mac mac = Mac.getInstance("HmacMD5");
            byte[] secretByte = KEY.getBytes("utf-8");
            byte[] dataBytes = content.getBytes("utf-8");

            SecretKey secret = new SecretKeySpec(secretByte, "HmacMD5");
            mac.init(secret);

            byte[] doFinal = mac.doFinal(dataBytes);
            byte[] hexB = new Hex().encode(doFinal);
            return new String(hexB, "utf-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
